package fyp.spedmew.backend.service;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Serving file from Google Blobstore service
 */
public class FileDeliverServlet extends HttpServlet{
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    private static final Logger log = Logger.getLogger(FileDeliverServlet.class.getName());

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        BlobKey blobKey = new BlobKey(req.getParameter("key"));
        BlobInfo blobInfo =  new BlobInfoFactory().loadBlobInfo(blobKey);

        // set response header
        res.setContentType(blobInfo.getContentType());
        res.setHeader("Content-Disposition", "filename=" + blobInfo.getFilename());

        blobstoreService.serve(blobKey, res);
    }
}
